/**
 * Created by LMN on 2016/9/14.
 *
 */
var net = require('net');
var config = require('./../config/index');
var LOG = require('./log.js').getLogger('receive-data');
var sendFun = null,
    _socket = null;
/**
 * Handle the data.
 * @param d, the data object.
 */
var handleData = function(d){
    //Send data to Master.
    if(sendFun) sendFun(d);
    //Save data if you need to.
};
/**
 * Interface for Master, called when Master send something to Worker.
 * @param obj, the data object.
 */
exports.receive = function(obj){
    if(!obj.hasOwnProperty('flag')) return;
    var msg = '';
    switch (obj.flag){
        case 0: {// $START
            msg+='$START,'+obj.code+'*';break;}
        case 1: {// $PAUSE
            msg+='$PAUSE,'+obj.code+','+obj.serial+'*';break;}
        case 2: {// $CONTINUE
            msg+='$CONTINUE,'+obj.code+','+obj.serial+'*';break;}
        case 3: {// $COMPLETED
            msg+='$COMPLETED,'+obj.code+'*';break;}
        case 5: { // $STATION, station
            obj.list.forEach(function (a) {
                a.users.forEach(function (user) {
                    if(a.type == 0)
                        msg+='$STATION,'+user.username+','+a.code+',0,'+a.latitude+','+a.longitude+','+a.altitude+','+a.port+'*';
                    else if(a.type == 1)
                        msg+='$STATION,'+user.username+','+a.code+',1,0,0,0,'+a.port+'*';
                })
            });
            break;
        }
    }
    //Send message to the socket.
    if(_socket && msg) _socket.write(msg);
};
/**
 * Cache the function which is used to send message to Master.
 * @param sf, the interface function of Master.
 */
exports.sendFunToWeb = function(sf){
    sendFun = sf;
};
/**
 * Start a TCP server.
 */
exports.startTcpServer = function(){
    var server = net.createServer();
    server.on('connection', function (socket) {
        LOG.info('Connection of actual : '+socket.remoteAddress+':'+socket.remotePort+' -connected');
        _socket = socket;
        socket.write('CONNECTED');
        socket.on('close', function () {
            LOG.info('Connection of actual : '+socket.remoteAddress+':'+socket.remotePort+' -disconnected');
            socket.end();
            _socket = null;
        });
        socket.on('error', function () {});
        socket.on('data', function (data) {
            var bags = data.toString().split('$');
            for(var i= 0,len=bags.length;i<len;i++){
                var bag = bags[i].split('*');
                if(bag.length!=2) continue;
                var d = bag[0].split(','), json = {};
                var flag = d[0];
                switch (flag){
                    case 'POS':{
                        var time = new Date(d[2]);
                        if(!time.getTime()) break;
                        json = {
                            flag: 4,
                            code: d[1]+'',
                            time: d[2],
                            mark: parseInt(d[3]),
                            model: parseInt(d[4]),
                            accuracy: (d[5]*1).toFixed(6)*1,
                            latitude: (d[6]*1).toFixed(8)*1,
                            longitude: (d[7]*1).toFixed(8)*1,
                            altitude: (d[8]*1).toFixed(6)*1,
                            speed_x: d[9]*1,
                            speed_y: d[10]*1,
                            speed_z: d[11]*1
                        };
                        break;
                    }
                }
                if(json.hasOwnProperty('flag')) handleData(json);
            }
        });
    });
    server.listen(config.tcp.port, config.tcp.host, function () {
        console.log('TCP server listen on '+config.tcp.host+':'+config.tcp.port+'.');
    });
};